package com.idc.resource.util;

import lombok.extern.slf4j.Slf4j;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;

import javax.net.ssl.*;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * retrofit 工具类
 * Created by Lijing on 2017/3/2.
 */
@Slf4j
public class RetrofitUtil {
    public static Retrofit createRetrofit(final Map<String,String> header, String apiBaseUrl) {

        Interceptor interceptor  = chain -> {
            Request.Builder b = chain.request().newBuilder();
            if(header!=null) {
                for (String key : header.keySet()) {
                    b.addHeader(key, header.get(key));
                }
            }
            return chain.proceed(b.build());

        };

        X509TrustManager xtm = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        };

        SSLContext sslContext = null;
        try {
            sslContext = SSLContext.getInstance("SSL");

            sslContext.init(null, new TrustManager[]{xtm}, new SecureRandom());

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
        HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };


        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.interceptors().add(interceptor);

        OkHttpClient client = builder
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .sslSocketFactory(sslContext.getSocketFactory())
                .hostnameVerifier(DO_NOT_VERIFY)
                .build();

        Retrofit retrofit = new Retrofit
                .Builder()
                .baseUrl(apiBaseUrl)
                .addConverterFactory(JacksonConverterFactory.create())
                .client(client)
                .build();

        return retrofit;
    }

    public static <T> T getResult(Call<Result<T>> call){
        try {
            retrofit2.Response<Result<T>> response = call.execute();
            log.info("http code :{}",response.code());
            if(response.code()==200){
                Result<T> result = response.body();
                if(result.isSuccess()){
                    return result.getData();
                }
                log.error("{}",result);
            }else {
                log.info("http 请求失败 error :{}",response.errorBody().string());
                return null;
            }
        } catch (IOException e) {
            log.error("http请求失败:",e);
        }
        return null;
    }
}
